package cn.com.bo.util.crypto;

import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.binary.Base64;

public class Base64Util {
    /**
     * 加密
     * @param str
     * @return
     */
    public static String getBase64(String str) {
        byte[] b = null;
        try {
            b = str.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (b != null) {
        	return getBase64(b);
        }
        return null;
    }
    
    public static String getBase64(byte[] str) {
    	String s = null;
        if (str != null) {
            s = new Base64().encodeAsString(str);
        }
        return s;
    }
    
    /**
     * 加密
     * @param str
     * @return
     */
    public static String getBase64(String str,String charset) {
        byte[] b = null;
        try {
            b = str.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (b != null) {
        	return getBase64(b);
        }
        return null;
    }

    /**
     * 解密
     * @param s
     * @return
     */
    public static String getFromBase64(String s) {
        byte[] b = null;
        String result = null;
        if (s != null) {
            Base64 decoder = new Base64();
            try {
                b = decoder.decode(s);
                result = new String(b, "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}